package zcw.com.lib_leet_code;

/**
 * Created by 朱城委 on 2021/8/31.<br><br>
 *
 * 中等：删除有序数组中的重复项 II
 */
public class Topic80 {
    public static void main(String[] args) {
        Topic80 instance = new Topic80();

        int[] array = new int[] {1,1,1,2,2,3};
        System.out.println(instance.removeDuplicates(array));

        array = new int[] {0,0,1,1,1,1,2,3,3};
        System.out.println(instance.removeDuplicates(array));
    }

    public int removeDuplicates(int[] nums) {
        if(nums.length < 3) {
            return nums.length;
        }

        int result = 2;
        for(int i = 2; i < nums.length; i++) {
            if(nums[i] != nums[result - 2]) {
                nums[result++] = nums[i];
            }
        }

        return result;
    }

    public int removeDuplicates2(int[] nums) {
        if(nums.length < 3) {
            return nums.length;
        }

        int counter = 0;
        int index = 0;
        while (index < nums.length) {
            if(index + 1 < nums.length && nums[index] == nums[index + 1]) {
                int repeat = nums[index];
                nums[counter++] = nums[index];
                nums[counter++] = nums[index + 1];

                while (index + 2 < nums.length && nums[index + 2] == repeat) {
                    nums[counter] = nums[index + 2];
                    index++;
                }

                index += 2;
            }
            else {
                nums[counter++] = nums[index++];
            }
        }

        return counter;
    }
}
